package com.etoak.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.enums.ResultEnum;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.web.properties.ImageProperties;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile pic) {
        if (ObjectUtils.isEmpty(pic) || pic.isEmpty()) {
            return ResultVO.failed(ResultEnum.FILE_NULL_ERROR);
        }

        String contentType = pic.getContentType();;
        if (!imageProperties.getTypes().contains(contentType)) {
            String message = imageProperties.getTypes().stream().map(x -> x.substring(x.lastIndexOf("/") + 1)).collect(Collectors.joining("、"));
            return ResultVO.failed(ResultEnum.FILE_NULL_ERROR.getCode(), "仅支持" + message);
        }

        String originalFilename = pic.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + suffix;
        File file = new File(imageProperties.getLocation());
        if (!file.exists()) {
            file.mkdirs();
        }
        File destFile = new File(file, fileName);
        try {
            pic.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String path = imageProperties.getPrefix().endsWith("/") ? imageProperties.getPrefix() + fileName : imageProperties.getPrefix() + "/" + fileName;
        return ResultVO.success(path);
    }
}
